package com.lagou.rpc.util;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ZkUtil {
    private CuratorFramework zkClient;

    private static final String path = "/lg-rpc";

    private static String address = "192.168.174.128:2181";

    public ZkUtil() {
        zkClient = getClient();
    }

    public static CuratorFramework getClient() {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString(address)
                .sessionTimeoutMs(5000)
                .connectionTimeoutMs(3000)
                .retryPolicy(retryPolicy)
                .namespace("base")
                .build();
        client.start();
        return client;
    }

    // 注册服务
    public void register(String serviceAddress) {
        try {
            String addressPath = path + "/" + serviceAddress;
            zkClient.create().creatingParentContainersIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(addressPath, (System.currentTimeMillis() + "-0").getBytes(StandardCharsets.UTF_8));
            System.out.println("服务节点注册成功：" + addressPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取所有服务列表
    public Map<String, String> getAddressList() {
        Map<String, String> nodeMap = new HashMap<>();
        List<String> nodeList = new ArrayList<>();
        try {
            nodeList = zkClient.getChildren().forPath(path);
            for (String address : nodeList) {
                String nodePath = path + "/" + address;
                byte[] bytes = zkClient.getData().forPath(nodePath);
                String nodeData = new String(bytes);
                nodeMap.put(nodePath, nodeData);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return nodeMap;
    }

    //更新服务
    public void updateNodeData(String serviceAddress, String data) {
        try {
            String nodePath = serviceAddress;
            zkClient.setData().forPath(nodePath, data.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
